package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	. "github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"net/http"
	"strconv"
	"time"
	"zlxBook/Dao"
	"zlxBook/Response"
	"zlxBook/db"
	"zlxBook/model"
)

//分类接口
type InterfaceCategoryController interface {
	//增删改查
	Create(context *Context)
	Get(context *Context)
	Update(context *Context)
	Delete(context *Context)
}

//分类结构体实现上面的接口
type CategoryController struct {
	DB *gorm.DB
}

func CreateNewCategooryController() InterfaceCategoryController {

	db.DB.AutoMigrate(model.Category{})
	return CategoryController{DB: db.DB}

}
func (c CategoryController) Create(context *Context) {
	category := &model.Category{
		Name:     context.PostForm("name"),
		CreateAt: time.Now(),
		UpdateAt: time.Now(),
	}
	context.Bind(&category)
	if category.Name == "" {
		fmt.Println("输入错误，名字要填")
	} else {
		err := Dao.AddCategory(category)
		if err != nil {
			panic(err)
			return
		}
		context.JSON(http.StatusOK, gin.H{
			"msg": "成功添加",
		})
	}
}
func (c CategoryController) Get(context *Context) {
	fmt.Println("到这里了")
	categories := []*model.Category{}
	categories, err := Dao.GetCategories()
	if err != nil {
		context.JSON(http.StatusOK, Response.MessageMaker("获取消息出错"))
	}
	//response.Succces(ctx, gin.H{"categories": categories}, "获取分类成功！")
	context.JSON(http.StatusOK, gin.H{"msg": categories})
}
func (c CategoryController) Update(context *Context) {
	id, _ := strconv.Atoi(context.PostForm("id"))
	category := &model.Category{
		ID:       uint(id),
		Name:     context.PostForm("name"),
		CreateAt: time.Now(),
		UpdateAt: time.Now(),
	}
	//context.Bind(&category)
	if category.Name == "" {
		context.JSON(http.StatusOK, gin.H{"code": "命名为空"})
		return
	} else {
		Dao.UpdateCategory(category)
		context.JSON(http.StatusOK, Response.MessageMaker("成功修改文件"))
	}

}
func (c CategoryController) Delete(context *Context) {
	//id,_:=strconv.Atoi(context.PostForm("id"))
	id, _ := strconv.Atoi(context.Param("id"))
	fmt.Println("id为", id)
	err := Dao.DeleteCategoryById(id)
	if err != nil {
		context.JSON(http.StatusOK, Response.MessageMaker("删除出错"+err.Error()))
	}
}
